package com.huangd.platform.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huangd.platform.modules.sys.dao.SysUserTokenDao;
import com.huangd.platform.modules.sys.entity.SysUserTokenEntity;
import com.huangd.platform.modules.sys.oauth2.TokenGenerator;
import com.huangd.platform.common.utils.DateUtils;
import com.huangd.platform.common.utils.PageUtils;
import com.huangd.platform.common.utils.Query;
import com.huangd.platform.common.utils.R;
import com.huangd.platform.modules.sys.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
    @Resource
    SysUserTokenService userTokenService;

    //15天后过期
    private final static int EXPIRE = 3600 * 24 * 15;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysUserTokenEntity> page = this.page(
                new Query<SysUserTokenEntity>().getPage(params),
                new QueryWrapper<SysUserTokenEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public R createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        // 保存token

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = this.getById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(DateUtils.addDays(new Date(), 15));
            tokenEntity.setUpdateTime(new Date());

            //保存token
            this.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(new Date());
            tokenEntity.setExpireTime(DateUtils.addDays(new Date(), 15));

            //更新token
            this.updateById(tokenEntity);
        }
        //redisTemplate.opsForValue().set(key, userId + "", EXPIRE, TimeUnit.SECONDS);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", EXPIRE);
        R r = R.ok(map);

        return r;
    }

    @Override
    public void logout(String token) {
        // 删除redis token
        //String key = "dpzj:platform:token:" + token;
        //redisTemplate.delete(key);
        baseMapper.removeByToken(token);
    }

}